package org.geeks.gsredisson.api;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("hello")
@Slf4j
public class HelloApi {

  private Boolean flag = true;

  @Autowired private RedissonClient redissonClient;

  @GetMapping
  public String hello() {
    return "Hello";
  }

  @GetMapping("safe")
  public void safe() {
    RLock lock = redissonClient.getLock("HelloApi.hello");

    Boolean lockFlag = lock.tryLock();

    try {
      if (lockFlag) {
        if (flag) {
          flag = false;
          log.info("Execute ~");
        }
      }
    } finally {
      if (lockFlag) {
        lock.unlock();
      }
    }
  }

  @GetMapping("unsafe")
  public void unsafe() {
    if (flag) {
      flag = false;
      log.info("Execute ~");
    }
  }

  @GetMapping("reset")
  public void reset() {
    flag = true;
    log.info("-------------------------------------------------");
  }
}
